package com.ukao.pad.ui.stokin;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;


import com.ukao.pad.R;
import com.ukao.pad.adapter.CameraPhotoAdapter;
import com.ukao.pad.base.MvpActivity;
import com.ukao.pad.bean.ProductRelImgBean;
import com.ukao.pad.listener.OnItemChildClickListener;
import com.ukao.pad.presenter.CameraPesenter;
import com.ukao.pad.utils.BitmapUtils;
import com.ukao.pad.utils.CameraUtil;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.FileUtils;
import com.ukao.pad.utils.L;
import com.ukao.pad.utils.T;
import com.ukao.pad.utils.UploadUtils;
import com.ukao.pad.view.CameraView;
import com.ukao.pad.widget.StateImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 商品录入拍照界面
 */
public class CameraActivity extends MvpActivity<CameraPesenter> implements CameraView, SurfaceHolder.Callback {
    @BindView(R.id.surfaceView)
    SurfaceView surfaceView;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.finish_btn)
    StateImageView finishBtn;
    @BindView(R.id.img_camera)
    StateImageView imgCamera;
    private Camera mCamera;
    private SurfaceHolder mHolder;
    private int mCameraId = 0;
    private Context context;
    //屏幕宽高
    private int screenWidth;
    private int screenHeight;
    private String photoPath;
    private CameraPhotoAdapter mCameraPhotoAdapter;
    private SoundPool mSoundPool;
    private int outgoing;

    private UploadUtils mUploadUtils;
    private String orderProId;
    private ArrayList<ProductRelImgBean> mPhotoData;
    private  List  uploadData=new ArrayList();/*上传图片集合*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        ButterKnife.bind(this);
        context = this;
        //獲取設備信息
        getCameraInfo();
        initView();
        initData();
        initListener();
        takeCamerPhotoSoundPool();
    }

    @Override
    protected CameraPesenter createPresenter() {
        return new CameraPesenter(this);
    }

    protected void initView() {
        orderProId=getIntent().getStringExtra(ARG_PARAM1);
        mPhotoData= getIntent().getParcelableArrayListExtra(ARG_PARAM2);
        mHolder = surfaceView.getHolder();
        mHolder.addCallback(this);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mCameraPhotoAdapter=new CameraPhotoAdapter(this,mPhotoData);
        recyclerView.setAdapter(mCameraPhotoAdapter);

    }

    @Override
    protected void initListener() {
        super.initListener();
        mCameraPhotoAdapter.setOnItemChildClickListener(mOnItemChildClickListener);
    }


    private OnItemChildClickListener mOnItemChildClickListener=new OnItemChildClickListener() {
        @Override
        public void onChildItemClick(int id, int pos) {
            switch (id) {
                case R.id.image_remove:
                    ProductRelImgBean item = mCameraPhotoAdapter.getItem(pos);
                    mvpPresenter.deleteRelImg(item);
                    break;
            }
        }
    };

    public String getPhotoSavePath() {
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String pathString = "";
        if (dcim.exists()) {
            pathString = dcim + "/ukaoPOS/XKXPhoto/";
        } else {
            pathString = "/sdcard/ukaoPOS/XKXPhoto/";
        }
        File videoPathFile = new File(pathString);
        if (!videoPathFile.exists()) {
            videoPathFile.mkdirs();
        }
        return pathString;
    }

    private void initData() {
        photoPath = getPhotoSavePath();
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;

    }


    @SuppressLint("NewApi")
    public   void  takeCamerPhotoSoundPool(){
        SoundPool.Builder builder = new SoundPool.Builder();
        //传入音频数量
        builder.setMaxStreams(2);
        //AudioAttributes是一个封装音频各种属性的方法
        AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
        //设置音频流的合适的属性
        attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
        //加载一个AudioAttributes
        builder.setAudioAttributes(attrBuilder.build());
        mSoundPool= builder.build();
        outgoing=mSoundPool.load(this, R.raw.success, 1);
    }

    private int playCallSounds() {
        try {
            // 播放
            int id = mSoundPool.play(outgoing, // 声音资源
                    1.0f, // 左声道
                    1.0f, // 右声道
                    1, // 优先级，0最低
                    0, // 循环次数，0是不循环，-1是永远循环
                    1); // 回放速度，0.5-2.0之间。1为正常速度
            return id;
        } catch (Exception e) {
            return -1;
        }
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//
//        if (mCamera == null) {
//            mCamera = getCamera(mCameraId);
//            if (mCamera==null){
//
//                showError();
//                return;
//            }
//            if (mHolder != null) {
//                startPreview(mCamera, mHolder);
//            }
//        }
//    }

    private void showError() {
        T.show(getResources().getString(R.string.unconnected_camera));
        finish();
    }

    /**
     * 清除相机数据
     */
    private void cleanCameraData( ) {
        try {
            L.i("清除数据时=");
            //system/app系统自带的应用程序，无法删除。
            // data/app用户程序安装的目录，有删除权限。安装时把apk文件复制到此目录。
            Process su = Runtime.getRuntime().exec("su");
            String cmd = "rm -r " + "/data/data/" +"com.android.camera2";
            cmd = cmd + "\n exit\n";
            //以下两句代表重启设备
            //cmd ="reboot";
            //cmd = cmd + "\n exit\n";
            su.getOutputStream().write(cmd.getBytes());
            if ((su.waitFor() != 0)) {

            }
        } catch (Exception e) {
            L.i("清除数据时=" + e.toString());
        }



    }
    @Override
    protected void onPause() {
        super.onPause();
        cleanCameraData();
        releaseCamera();
    }

    /**
     * 获取Camera实例
     *
     * @return
     */
    private Camera getCamera(int id) {
        Camera camera = null;
        try {
            camera = Camera.open(id);
        } catch (Exception e) {

        }
        return camera;
    }

    /**
     * 预览相机
     */
    private void startPreview(Camera camera, SurfaceHolder holder) {
        try {
            setupCamera(camera);
//            camera.setPreviewDisplay(holder);  /*那相机画面设置到holder上*/
            //亲测的一个方法 基本覆盖所有手机 将预览矫正
//            CameraUtil.getInstance().setCameraDisplayOrientation(this, mCameraId, camera);
            camera.startPreview();
        } catch (Exception e) {

            e.printStackTrace();
        }
    }


    private void captrue() {
        playCallSounds();
        mCamera.takePicture(null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                //将data 转换为位图 或者你也可以直接保存为文件使用 FileOutputStream
                //这里我相信大部分都有其他用处把 比如加个水印
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                Bitmap saveBitmap = CameraUtil.getInstance().setTakePicktrueOrientation(mCameraId, bitmap);

                saveBitmap = Bitmap.createScaledBitmap(saveBitmap, screenWidth, screenHeight, true);

                saveBitmap = Bitmap.createBitmap(saveBitmap, 0, 0, screenWidth, screenHeight);

                String img_path = photoPath + System.currentTimeMillis() + ".jpeg";

                BitmapUtils.saveJPGE_After(context, saveBitmap, img_path, 100);

                if (!bitmap.isRecycled()) {
                    bitmap.recycle();
                }

                if (!saveBitmap.isRecycled()) {
                    saveBitmap.recycle();
                }
                compressWithLs(img_path);
                startPreview(mCamera, mHolder);
            }
        });
    }
    /**
     * 压缩图片 Listener 方式
     */
    private void compressWithLs(final String photos) {
        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onSuccess(File file) {
                        mPhotoData.add(0, new ProductRelImgBean(file.getPath()));
                        mCameraPhotoAdapter.setDatas(mPhotoData);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mPhotoData.add(0, new ProductRelImgBean(photos));
                        mCameraPhotoAdapter.setDatas(mPhotoData);

                    }
                }).launch();
    }

    public String getPath() {
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String pathString = "";
        if (dcim.exists()) {
            pathString = dcim + "/ukaoPOS/compressImage/";
        } else {
            pathString = "/sdcard/ukaoPOS/compressImage/";
        }
        File videoPathFile = new File(pathString);
        if (!videoPathFile.exists()) {
            videoPathFile.mkdirs();
        }
        return pathString;
    }

    /**
     * 设置
     */
    private void setupCamera(Camera camera) {
        try {
            Camera.Parameters parameters = camera.getParameters();
            if (parameters.getSupportedFocusModes().contains(
                    Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            }
            //  camera.cancelAutoFocus();//只有加上了这一句，才会自动对焦。
            //这里第三个参数为最小尺寸 getPropPreviewSize方法会对从最小尺寸开始升序排列 取出所有支持尺寸的最小尺寸
            Camera.Size previewSize = CameraUtil.getInstance().getPropPictureSize(parameters.getSupportedPreviewSizes(), 800);
            L.i("previewSize.height=" + previewSize.height + "previewSize.width=" + previewSize.width);
            parameters.setPreviewSize(previewSize.width, previewSize.height);

            Camera.Size pictrueSize = CameraUtil.getInstance().getPropPictureSize(parameters.getSupportedPictureSizes(), 800);
            parameters.setPictureSize(pictrueSize.width, pictrueSize.height);
            camera.setParameters(parameters);
        }catch (Exception  e){
            showError();
        }
    }

    /**
     * 释放相机资源
     */
    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }
    private void getCameraInfo(){
        try{
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            int cameracount = Camera.getNumberOfCameras();
//            L.i("你的手机一共有" + cameracount + "个摄像头");
//            T.show("你的手机一共有" + cameracount + "个摄像头");
            for (int cameranum = 0; cameranum < cameracount; cameranum++) {
                Camera.getCameraInfo(cameranum, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    mCameraId = 1;
//                    L.i("你的手机有前置");
                } else if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
//                    L.i("有后");
                    mCameraId = 0;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
//        if (holder!=null){
//            startPreview(mCamera, holder);
//        }else{
//            showError();
//        }
        try {
            if (mCamera == null) {
                //获取摄像头的信息 摄像头的数量
                new Camera.CameraInfo();
                int cameracount = Camera.getNumberOfCameras();
                L.i(cameracount+" 个数");
                 mCamera = getCamera(mCameraId);//开启相机
                 if (mCamera==null){
                    showError();
                    return;
                }
                mCamera.setPreviewDisplay(holder);//摄像头画面显示在Surface上
            }
        } catch (Exception e) {
            e.printStackTrace();
            showError();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (holder!=null){
//            mCamera.stopPreview();
            startPreview(mCamera, holder);
        }else{
            showError();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();
    }

    @OnClick({R.id.finish_btn, R.id.img_camera,R.id.back_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.finish_btn:
                uploadData.clear();
                for (ProductRelImgBean mImgBean : mPhotoData) {
                    if (CheckUtils.isHttp(mImgBean.getCameraImg())){
                        uploadData.add(mImgBean.getCameraImg());
                    }
                }
                if (CheckUtils.isEmpty(uploadData)){
                    int    photoCount=0;
                    for (ProductRelImgBean productRelImgBean : mCameraPhotoAdapter.getDatas()) {
                        if (!CheckUtils.isHttp(productRelImgBean.getCameraImg())){
                            photoCount=photoCount+1;
                        }
                    }
                    setPhotoResult(photoCount);
                    finish();
                    return;
                }
                mvpPresenter.qiniutoken();
                break;
            case R.id.img_camera:
                if (mCameraPhotoAdapter.getDatas().size()==10){
                    T.show(getResources().getString(R.string.maximum_ten));
                    return;
                }
                if (mHolder!=null&&mCamera!=null){
                    captrue();
                }
                break;

            case   R.id.back_btn:
                int    photoCount=0;
                for (ProductRelImgBean productRelImgBean : mCameraPhotoAdapter.getDatas()) {
                    if (!CheckUtils.isHttp(productRelImgBean.getCameraImg())){
                        photoCount=photoCount+1;
                    }
                }
                setPhotoResult(photoCount);
                finish();
                break;
        }
    }

    /**
     *
     * @param token  七牛token
     */
    @Override
    public void loadQiLitoken(String token) {
        if (this.mUploadUtils== null) {
            this.mUploadUtils = new UploadUtils();
        }
        mUploadUtils.startImageUpload(this,token,uploadData,mOnOSSFileUpload);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSoundPool!=null){  mSoundPool.release();  }
    }

    private UploadUtils.OnOSSFileUploadFinish mOnOSSFileUpload= new UploadUtils.OnOSSFileUploadFinish() {
        @Override
        public void OnUploadFinish(String image, String video, String videoImage) {
            L.i("image="+image);
            mvpPresenter.addphotoOrder(orderProId,image);

        }
    };
    @Override
    public void loadFail(String message) {
        T.show(message);
    }

    @Override
    public void addphotoSucceed( ) {
        FileUtils.deleteAllInDir(getPhotoSavePath());
        FileUtils.deleteAllInDir(getPath());
        setPhotoResult(mCameraPhotoAdapter.getDatas().size());
    }

    private void setPhotoResult(int  photoCount ) {
        Intent   mIntent=new Intent();
        mIntent.putExtra(ARG_PARAM1,orderProId);
        mIntent.putExtra(ARG_PARAM2,photoCount);
        setResult(RESULT_OK,mIntent);
        finish();
    }

    /**
     *
     * @param item  删除标识
     *
     */
    @Override
    public void deletePhoto(ProductRelImgBean item ) {
        T.show("删除成功");
        mCameraPhotoAdapter.getDatas().remove(item);
        mCameraPhotoAdapter.notifyDataSetChanged();
    }
}
